package cate.game.server.schedule.task;

import cate.game.ManyGame;
import cp.solution.business.game.cmd.ProcessTaskEntity;
import cp.solution.manage.PrimaryClient;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public abstract class ProcessTaskExecutable {

    static ExecutorService es = Executors.newSingleThreadExecutor();

    protected ProcessTaskEntity task;
    protected ManyGame games;
    protected PrimaryClient pc;

    public ProcessTaskExecutable init(ProcessTaskEntity task, ManyGame games, PrimaryClient pc) {
        this.task = task;
        this.games = games;
        this.pc = pc;
        return this;
    }

    protected boolean cancelWhenTimeout() {
        return true;
    }

    protected long timeoutMs() {
        return 6000l;
    }

    public String exe() throws Exception {
        Future<String> future = es.submit(this::exeImpl);
        String str = null;
        try {
            str = future.get(timeoutMs(), TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            log.error("exe InterruptedException", e);
        } catch (ExecutionException e) {
            log.error("exe ExecutionException", e);
        } catch (TimeoutException e) {
            log.error("exe TimeoutException", e);
            if(cancelWhenTimeout()) {
                future.cancel(true);
                log.info("强行取消了任务");
            }
        }
        return str;
    }

    protected abstract String exeImpl() throws Exception;
}
